<template>
  <div class="app-container">
    <el-form ref="queryRef" :inline="true" label-width="68px">
      <el-form-item label="订单编号" prop="institutionName" >
        <el-input :value="route.query.purchaseOrderNo" disabled style="width: 240px;"/>
      </el-form-item>
      <el-form-item label="应付金额" prop="description">
        <el-input :value="route.query.amount" disabled />
      </el-form-item>
    </el-form>

    <div>
      <el-button
        type="primary"
        plain
        :icon="Plus"
        style="margin: 10px 0"
        @click="handleAdd"
        :disabled="disabled"
        >新增付款</el-button
      >

      <el-table
        :data="tableData"
        show-summary
        border
        style="width: 100%; background-color: #fff"
        :summary-method="handleSummary"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="payDescription"
          label="付款说明"
          width="300"
        />
        <el-table-column prop="payAmount" label="付款金额" width="200" />
        <el-table-column prop="tradeNo" label="交易单号" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" @click="handleShow(scope.row)">查看</el-button>
            <el-button
              type="primary"
              @click="handleUpdate(scope.row)"
              :disabled="disabled"
              >修改</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加或修改分批计费(应收)对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="paymentRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="付款金额" prop="payAmount">
          <el-input
            placeholder="请输入付款金额"
            v-model="form.payAmount"
          />
        </el-form-item>
        <el-form-item label="付款说明" prop="payDescription">
          <el-input
            placeholder="请输入付款说明"
            v-model="form.payDescription"
          />
        </el-form-item>
        <el-form-item label="付款时间" prop="payTime">
          <el-date-picker
            clearable
            v-model="form.payTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择付款时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="交易单号" prop="tradeNo">
          <el-input placeholder="请输入交易单号" v-model="form.tradeNo" />
        </el-form-item>
        <el-form-item label="附件" prop="other">
                  <!-- <el-upload
            v-model:file-list="other"
            class="upload-demo"
            action="http://localhost:8080/finance/billing/other"
            :before-upload="beforeUpload"
            multiple
            :limit="3"
          >
            <el-button type="primary" >附件上传</el-button>
          </el-upload> -->

          <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeUpload"
        >
          <img v-if="otherUrl" :src="otherUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看图片 -->
    <el-dialog
    v-model="otherShow"
    title="查看图片"
    width="500"
  >
    <el-image
    v-if="otherUrl"
    style="width: 100px; height: 100px"
    :src="otherUrl"
    :zoom-rate="1.2"
    :max-scale="7"
    :min-scale="0.2"
    fit="cover"
  />
  <span v-else>无附件图片</span>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="otherShow = false">返回</el-button>
        <el-button type="primary" @click="otherShow = false">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  </div>
</template>

<script setup>
import { useRoute } from "vue-router";
import {getPayment,addPayment,updatePayment,selectSumAmount,getPaymentById} from "@/api/finance/payment.js";
import { Plus } from "@element-plus/icons-vue";
import { ref } from "vue";

const tableData = ref([]);
const { proxy } = getCurrentInstance();
const route = useRoute();
const open = ref(false);
const title = ref();
const disabled = ref(false);
const other = ref()

//查看图片
const otherShow = ref(false)
//附件图片地址
const otherUrl = ref()
const data = reactive({
  form: {},
  rules: {
    accountsPayableId: [
      { required: true, message: "关联应付账款表id不能为空", trigger: "blur" }
    ],
    payAmount: [
      { required: true, message: "付款金额不能为空", trigger: "blur" }
    ],
    payTime: [
      { required: true, message: "付款日期不能为空", trigger: "blur" }
    ],
    tradeNo: [
      { required: true, message: "交易单号不能为空", trigger: "blur" }
    ],
  }
});
const { form, rules } = toRefs(data);


/** table表格合计行*/
function handleSummary(param) {
  const { columns, data } = param;
  const sum = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sum[index] = h("div", ["合计"]);
      return;
    }
  });
  let number = 0;
  data.forEach((item) => {
    number += item.payAmount;
  });
  
  sum[2] = number;

  return sum;
}

function handleAvatarSuccess( response,uploadFile){
  console.log(uploadFile);
  
  // imageUrl.value = URL.createObjectURL(!uploadFile.raw)
}

/** 查看图片 */
function handleShow(row){
  otherUrl.value = row.other
  otherShow.value =true
}

/** 上传图片 */
function beforeUpload(file){
  let formData = new FormData()
  formData.append('other',file)
  uploadOther(formData).then(resp => {
    form.value.other = resp.msg
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getPaymentById(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改付款记录";
    getAllAmount();
  });
}

/** 打开新增框*/
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增付款记录";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["paymentRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updatePayment(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
          getAllAmount();
        });
      } else {
        form.value.accountsPayableId = route.query.id;
        addPayment(form.value).then((resp) => {
          reset();
          open.value = false;
          getList();
          proxy.$modal.msgSuccess("新增成功");
          getAllAmount();
        });
      }
    }
  });
}



// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    accountsPayableId: null,
    payAmount: null,
    payDescription: null,
    payTime: null,
    tradeNo: null,
    other: null
  };
  proxy.resetForm("paymentRef");
}

/** 获取当前应付单的总收款金额 */
function getAllAmount() {
  selectSumAmount(route.query.id).then((resp) => {
    if (resp.data >= route.query.amount) {
      disabled.value = true;
    }
  });
}

/** 获取收款记录 */
function getList() {
  getPayment(route.query.id).then((resp) => {
    tableData.value = resp.data;
  });
  getAllAmount()
}

getList();
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width:120px;
  height: 120px;
  text-align: center;
}
</style>